package com.shadow.baiqun.delegate.send;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.receive.adapter.SendGoodsAdapter;
import com.shadow.baiqun.delegate.send.detail.SendDetailDelegate;
import com.shadow.baiqun.view.TableHeadView;
import com.shadow.core.delegate.bottom.BottomItemDelegate;
import com.shadow.core.event.StartBrotherFragmentEvent;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.ui.recycler.BaseDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * @author zy
 * on 2018/5/19
 */
public class SendDelegate extends BottomItemDelegate {
    private static final int PAGE_SIZE = 50;
    @BindView(R2.id.lv_title)
    TableHeadView mHeadView;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.swipe_layout)
    SwipeRefreshLayout mRefreshLayout;
    SendGoodsAdapter mSendGoodsAdapter;
    private int mNextRequestPage = 1;
    private boolean isRequesting = false;
    private Disposable mDisposable;

    @Override
    public Object setLayout() {
        return R.layout.delegate_send;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        List<String> list = new ArrayList<>();
        list.add("车牌号");
        list.add("车次");
        list.add("添加人");
        list.add("添加时间");
        mHeadView.setHeaders(list);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        mSendGoodsAdapter = new SendGoodsAdapter(getContext(),
                R.layout.item_send_goods, null);
        mSendGoodsAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources()
                .getColor(R.color.color_white_light_gray), 1));
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources().getColor(R.color.color_white_light_gray),
                1));
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                SendGoodsEntity sendGoodsEntity = (SendGoodsEntity) adapter.getItem(position);
                if (sendGoodsEntity != null) {
                    String donUserId = sendGoodsEntity.getDoneUserid();
                    EventBus.getDefault().post(new StartBrotherFragmentEvent(
                            SendDetailDelegate.create(sendGoodsEntity.getId(),
                                    (donUserId == null || donUserId.isEmpty()))
                    ));
                }
            }
        });
        mRecyclerView.setAdapter(mSendGoodsAdapter);
        mSendGoodsAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
        if (mSendGoodsAdapter.getEmptyView() != null) {
            mSendGoodsAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
    }

    private void requestData(final boolean isRefresh) {
        mDisposable = RxRestClient.builder()
                .url("WMS/backstage/sendCar/carList")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mSendGoodsAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        SendGoodsConverter sendGoodsConverter = new SendGoodsConverter();
                        setData(isRefresh, sendGoodsConverter.convert(response));
                        isRequesting = false;
                        mRefreshLayout.setRefreshing(false);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        isRequesting = false;
                        mRefreshLayout.setRefreshing(false);
                        mSendGoodsAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                    }
                })
                .params("pageNum", mNextRequestPage)
                .params("pageSize", PAGE_SIZE)
                .build()
                .unRestGet();
    }

    private void loadMore() {
        requestData(false);
    }

    private void setData(boolean isRefresh, List<SendGoodsEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mSendGoodsAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mSendGoodsAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mSendGoodsAdapter.loadMoreEnd(isRefresh);
        } else {
            mSendGoodsAdapter.loadMoreComplete();
        }
    }

    //刷新
    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mSendGoodsAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refresh();
    }

}
